package org.kzwl.comm.advice;

import lombok.extern.slf4j.Slf4j;

import org.kzwl.comm.pojo.ResponseData;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @Description: 异常捕获
 * @Author: Mao.mao
 * @date: 2020/6/6
 */
@Slf4j
@ControllerAdvice
public class CommonControllerAdvice {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ResponseData<Void> errorHandle(Exception e) {

        if (e instanceof BizException || e instanceof ParameterException) {
            ResponseData<Void> responseData = new ResponseData<>();
            responseData.setMsg(e.getMessage());
            responseData.setCode(Consts.Result.BIZ_ERROR.getCode());
            log.error("异常" + e.getMessage());
            return responseData;
        } else if (e instanceof MethodArgumentNotValidException) {
            ResponseData<Void> responseData = new ResponseData<>();
            String serverErrorMsg =
                    (e.getMessage().substring(e.getMessage().lastIndexOf("default message [") + 17, e.getMessage().lastIndexOf("]]")));
            log.info("ser:[{}]", serverErrorMsg);
            responseData.setMsg(serverErrorMsg);
            responseData.setCode(Consts.Result.BIZ_ERROR.getCode());
            return responseData;
        } else {
            log.error("", e);
            ResponseData<Void> responseData = new ResponseData<>();
            responseData.setMsg(Consts.Result.BIZ_ERROR.getMsg());
            responseData.setCode(Consts.Result.BIZ_ERROR.getCode());
            return responseData;
        }
    }
}

